const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const crypto = require('crypto');
const config = require('./config');

const app = express();
const port = config.server.port;

// 启用CORS
app.use(cors());
app.use(express.json());

const userSessionMap = {};

// 清理过期的会话
const cleanExpiredSessions = () => {
  const now = Date.now();
  Object.keys(userSessionMap).forEach(token => {
    const session = userSessionMap[token];
    if (now - session.createTime > config.session.expireTime) {
      delete userSessionMap[token];
    }
  });
};

// 定期清理过期会话
setInterval(cleanExpiredSessions, 60 * 60 * 1000); // 每小时清理一次

// 读取JSON文件
async function readJsonFile(filename) {
  const filePath = path.join(__dirname, 'data', filename);
  const data = await fs.readFile(filePath, 'utf8');
  return JSON.parse(data);
}

// 获取轮播图
app.get('/api/banners', async (req, res) => {
  try {
    const data = await readJsonFile('banners.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取轮播图失败' });
  }
});

// 获取产品列表
app.get('/api/products', async (req, res) => {
  try {
    const data = await readJsonFile('products.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取产品列表失败' });
  }
});

// 获取分类列表
app.get('/api/categories', async (req, res) => {
  try {
    const data = await readJsonFile('categories.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取分类列表失败' });
  }
});

// 获取订单列表
app.get('/api/orders', async (req, res) => {
  try {
    const data = await readJsonFile('orders.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取订单列表失败' });
  }
});

// 创建订单
app.post('/api/orders', async (req, res) => {
  try {
    const orders = await readJsonFile('orders.json');
    const newOrder = {
      id: orders.orders.length + 1,
      orderNo: `20240315${String(orders.orders.length + 1).padStart(4, '0')}`,
      status: 0,
      ...req.body,
      createTime: new Date().toLocaleString()
    };
    orders.orders.push(newOrder);
    await fs.writeFile(
      path.join(__dirname, 'data', 'orders.json'),
      JSON.stringify(orders, null, 2)
    );
    res.json(newOrder);
  } catch (error) {
    res.status(500).json({ error: '创建订单失败' });
  }
});

// 更新订单状态
app.put('/api/orders/:id', async (req, res) => {
  try {
    const orders = await readJsonFile('orders.json');
    const orderId = parseInt(req.params.id);
    const orderIndex = orders.orders.findIndex(order => order.id === orderId);
    
    if (orderIndex === -1) {
      return res.status(404).json({ error: '订单不存在' });
    }

    orders.orders[orderIndex] = {
      ...orders.orders[orderIndex],
      ...req.body
    };

    await fs.writeFile(
      path.join(__dirname, 'data', 'orders.json'),
      JSON.stringify(orders, null, 2)
    );

    res.json(orders.orders[orderIndex]);
  } catch (error) {
    res.status(500).json({ error: '更新订单失败' });
  }
});

// 获取每周特权
app.get('/api/profile-privileges', async (req, res) => {
  try {
    const data = await readJsonFile('profile-privileges.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取每周特权失败' });
  }
});

// 获取乐享服务
app.get('/api/profile-services', async (req, res) => {
  try {
    const data = await readJsonFile('profile-services.json');
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: '获取乐享服务失败' });
  }
});

// 微信登录
app.post('/api/login', async (req, res) => {
  const { code, userInfo } = req.body;
  if (!code) {
    return res.status(400).json({ error: '缺少code' });
  }

  try {
    // 调用微信接口获取 openid
    const wxRes = await fetch(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.appid}&secret=${config.wx.secret}&js_code=${code}&grant_type=authorization_code`
    );
    
    if (!wxRes.ok) {
      throw new Error('微信接口请求失败');
    }

    const wxData = await wxRes.json();
    
    if (wxData.errcode) {
      console.error('微信登录失败:', wxData);
      return res.status(500).json({ 
        error: '微信登录失败', 
        detail: wxData.errmsg || '未知错误' 
      });
    }

    if (!wxData.openid) {
      return res.status(500).json({ 
        error: '获取openid失败', 
        detail: '微信返回数据中没有openid' 
      });
    }

    // 生成token
    const token = crypto.createHash('md5')
      .update(wxData.openid + Date.now())
      .digest('hex');

    // 存储用户会话信息
    userSessionMap[token] = { 
      openid: wxData.openid, 
      userInfo: userInfo || {}, 
      credit: 100,
      createTime: Date.now()
    };

    // 返回登录成功信息
    res.json({
      openid: wxData.openid,
      session_key: wxData.session_key,
      userInfo: userInfo || {},
      token
    });

  } catch (e) {
    console.error('登录异常:', e);
    res.status(500).json({ 
      error: '登录异常', 
      detail: e.message || '服务器内部错误' 
    });
  }
});

// 查询积分
app.get('/api/credit', (req, res) => {
  const token = req.headers['authorization'] || req.query.token;
  if (!token || !userSessionMap[token]) {
    return res.status(401).json({ error: '未登录或token无效' });
  }

  // 检查token是否过期
  const session = userSessionMap[token];
  if (Date.now() - session.createTime > config.session.expireTime) {
    delete userSessionMap[token];
    return res.status(401).json({ error: '登录已过期' });
  }

  // 如果配置了自动续期，更新创建时间
  if (config.session.autoRenew) {
    session.createTime = Date.now();
  }

  res.json({ credit: session.credit });
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
}); 